<%--
  Created by IntelliJ IDEA.
  User: HQKS-004-05
  Date: 2017/12/14
  Time: 17:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" import="java.lang.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
    String path = request.getContextPath();
%>
<div class="row-fluid" style="height: inherit;margin:0px">
    <form id="inForm" class="form-horizontal" target="_ifr" style="margin-right:10px;">
        <input type="hidden" id="id" name="id" value="${packagemanagein.id}">
        <input type="hidden" id="state" name="state" value="${packagemanagein.state}">
        <div  class="row" style="margin:0;padding:0;">
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="packageInNo">翻入编号：</label>
                <div class="controls">
                    <div class="input-append span12" >
                        <input type="text" id="packageInNo" class="span10" name="packageInNo" value="${packagemanagein.packageInNo}"  placeholder="后台自动生成" readonly="readonly">
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="packageInName">翻入名称：</label>
                <div class="controls">
                    <div class="input-append span12 required">
                        <input id="packageInName" name="packageInName" type="text" value="${packagemanagein.packageInName}" placeholder="翻入名称" class="span10">
                    </div>
                </div>
            </div>
        </div>
        <div  class="row" style="margin:0;padding:0;">
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="packageId" >翻包编号：</label>
                <div class="controls">
                    <div class="span12 required" >
                        <input type="text" id="packageId" class="span10" name="packageId" value="${packagemanagein.packageId}" placeholder="翻包编号">
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="userId" >操作人：</label>
                <div class="controls">
                    <div class="span12 required" >
                        <input type="text" id="userId" class="span10" name="userId" value="${packagemanagein.userId}" placeholder="操作人">
                    </div>
                </div>
            </div>
        </div>
        <div  class="row" style="margin:0;padding:0;">
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="oprateTime" >入库时间：</label>
                <div class="controls">
                    <div class="required span12">
                        <input class="form-control date-picker" type="text" id="oprateTime" name="oprateTime"  placeholder="入库时间" value="${packagemanagein.oprateTime }">
                    </div>
                </div>
            </div>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="remark" >备注：</label>
                <div class="controls">
                    <div class="input-append   span12" >
                        <input class="span10" type="text" id="remark" name="remark"  maxlength="4"
                               placeholder="备注" value="${packagemanagein.remark}">
                    </div>
                </div>
            </div>
        </div>
        <div style="margin-left:10px;">
            <span class="btn btn-info"  onclick="saveForm()">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
            <span class="btn btn-info" id="formsub" onclick="submitPackageIn()">
		       <i class="ace-icon fa fa-check bigger-110"></i>提交
            </span>
        </div>
    </form>
    <div id="materialDiv" style="margin:10px;">
        <!-- 下拉框 -->
        <label class="inline" for="materialInfor">物料：</label>
        <input type="text" id="materialInfor" name="materialInfor" style="width:200px;margin-right:10px;" />
        <label class="inline" for="materiallocal">库位：</label>
        <input type="text" id="materiallocal" name="materiallocal" style="width:200px;margin-right:10px;" />
        <button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
            <i class="icon-plus" style="margin-right:6px;"></i>添加
        </button>
    </div>
    <!-- 表格div -->
    <div id="grid-div-c" style="width:100%">
        <!-- 	表格工具栏 -->
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
            <div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
        <!-- 物料详情信息表格 -->
        <table id="grid-table-c" style="width:100%;height:100%;"></table>
        <!-- 表格分页栏 -->
        <div id="grid-pager-c" style="margin:0px;"></div>
    </div>
</div>
<script type="text/javascript">
    var context_path = '<%=path%>';
    var saleId=$("#saleId").val();
    var oriDataDetail;
    var _grid_detail;        //表格对象
    var dynamicDefalutValue="c052aba68a874be98776786891f3047c";
    var lastsel2;
    $(".date-picker").datetimepicker({format: 'YYYY-MM-DD',useMinutes:true,useSeconds:true});
    $("#inForm").validate({
        ignore: "",
        rules:{
            "packageInName":{
                required:true,
                remote:"<%=path%>/packageIn/existsName?id="+$("#inForm #id").val()
            },
            "packageId":{
                required:true
            },
            "oprateTime":{
                required:true
            },
            "userId":{
                required:true
            },
        },
        messages: {
            "packageInName":{
                required:"请输入名称！",
                remote:"输入名称已存在！"
            },
            "packageId":{
                required:"请选择翻包编号！"
            },
            "oprateTime":{
                required:"请选择时间！"
            },
            "userId":{
                required :"请选择操作人"
            },
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        }
    });
    function saveForm() {
        var bean = $("#inForm").serialize();
        if($('#inForm').valid()){
            saveIn(bean);
        }
    }
    function saveIn(bean) {
        $.ajax({
            url : context_path + "/packageIn/save.do",
            type : "POST",
            data : bean,
            dataType : "JSON",
            success : function(data) {
                if (Boolean(data.result)) {
                    layer.msg("表头保存成功！", {icon : 1});
                    $("#inForm #id").val(data.id);
                    $("#inForm #packageInNo").val(data.packageInNo);
                    $("#inForm #state").val(data.state);
                    $("#grid-table_package").jqGrid("setGridParam", {
                        postData: {queryJsonString:""}
                    }).trigger("reloadGrid");
                } else {
                    layer.alert("保存失败，请稍后重试！", {icon : 2});
                }
            },
            error : function(XMLHttpRequest) {
                alert(XMLHttpRequest.readyState);
                alert("出错啦！！！");
            }
        });
    };
    //单元格编辑成功后，回调的函数
    var editFunction = function eidtSuccess(XHR){
        var data = eval("("+XHR.responseText+")");
        if(data["msg"]!=""){
            layer.alert(data["msg"]);
        }
        jQuery("#grid-table-c").jqGrid('setGridParam',
            {
                postData: {
                    id:$('#id').val(),
                    queryJsonString:""
                }
            }
        ).trigger("reloadGrid");
    };
    _grid_detail=jQuery("#grid-table-c").jqGrid({
        url : context_path + "/packageIn/detailList.do?pId="+$("#inForm #id").val(),
        datatype : "json",
        colNames : [ "详情主键","物料编号","物料名称","库位","数量"],
        colModel : [
            {name : "id",index : "id",width : 20,hidden:true},
            {name : "materialNo",index:"materialNo",width :20},
            {name : "materialName",index:"materialName",width : 20},
            {name : "locationName",index:"locationName",width : 40},
            {name : "amount", index: "amount", width: 40,editable : true,editrules: {custom: true, custom_func: numberRegex},
                editoptions: {
                    size: 25,
                    dataEvents: [
                        {
                            type: "blur",     //blur,focus,change.............
                            fn: function (e) {
                                var $element = e.currentTarget;
                                var $elementId = $element.id;
                                var rowid = $elementId.split("_")[0];
                                var id=$element.parentElement.parentElement.children[1].textContent;
                                var indocType = 1;
                                var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
                                if (!reg.test($("#"+$elementId).val())) {
                                    layer.alert("非法的数量！(注：可以有两位小数的正实数)");
                                    return;
                                }
                                $.ajax({
                                    url:context_path + "/packageIn/setAmount",
                                    type:"POST",
                                    data:{id:id,materialNo:$element.parentElement.parentElement.children[2].textContent,amount:$("#"+rowid+"_amount").val(),packageId:$("#inForm #packageId").val()},
                                    dataType:"json",
                                    success:function(data){
                                        if(Boolean(data.result)){
                                            $("#grid-table-c").jqGrid("setGridParam",
                                                {
                                                    url : context_path + "/packageIn/detailList.do?pId="+$("#inForm #id").val(),
                                                    postData: {queryJsonString:""} //发送数据  :选中的节点
                                                }
                                            ).trigger("reloadGrid");
                                            layer.msg("保存数量成功！");
                                        }else{
                                            layer.alert(data.msg);
                                        }
                                    }
                                });
                            }
                        }
                    ]
                }
            }
        ],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : "#grid-pager-c",
        sortname : "d.id",
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
        beforeRequest:function (){
            dynamicGetColumns(dynamicDefalutValue,'grid-table-c', $(window).width()-$("#sidebar").width() -7);
            //重新加载列属性
        },
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            oriDataDetail = data;
            $(window).triggerHandler('resize.jqGrid');
        },
        cellEdit: true,
        cellsubmit : "clientArray",
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid('#grid-pager-c',{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd("#grid-pager-c",{
        caption:"",
        buttonicon:"ace-icon fa fa-refresh green",
        onClickButton: function(){
            $("#grid-table-c").jqGrid('setGridParam',
                {
                    url:context_path + "/packageIn/detailList.do?pId="+$("#inForm #id").val(),
                    postData: {queryJsonString:""} //发送数据  :选中的节点
                }
            ).trigger("reloadGrid");
        }
    }).navButtonAdd('#grid-pager-c',{
            caption: "",
            buttonicon:"ace-icon fa icon-cogs",
            onClickButton : function (){
                jQuery("#grid-table-c").jqGrid('columnChooser',{
                    done: function(perm, cols){
                        dynamicColumns(cols,dynamicDefalutValue);
                        //cols页面获取隐藏的列,页面表格的值
                        $("#grid-table-c").jqGrid( 'setGridWidth', $("#grid-div-c").width()-3 );
                    }
                });
            }
        });

    $(window).on("resize.jqGrid", function () {
        $("#grid-table-c").jqGrid( "setGridWidth", $("#grid-div-c").width() - 3 );
        var height = $(".layui-layer-title",_grid_detail.parents(".layui-layer")).height()+
            $("#inForm").outerHeight(true)+$("#materialDiv").outerHeight(true)+
            $("#grid-pager-c").outerHeight(true)+$("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
          //$("#gview_grid-table-c .ui-jqgrid-titlebar").outerHeight(true)+
            $("#gview_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
            $("#grid-table-c").jqGrid('setGridHeight',_grid_detail.parents(".layui-layer").height()-height);
    });
    $(window).triggerHandler("resize.jqGrid");
    //将数据格式化成两位小数：四舍五入
    function formatterNumToFixed(value,options,rowObj){
        if(value!=null){
            var floatNum = parseFloat(value);
            return floatNum.toFixed(2);
        }else{
            return "0.00";
        }
    }
    //数量输入验证
    function numberRegex(value, colname) {
        var regex = /^\d+\.?\d{0,2}$/;
        reloadDetailTableList();
        if (!regex.test(value)) {
            return [false, ""];
        }
        else  return [true, ""];
    }

    //清空物料多选框中的值
    function removeChoice(){
        $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
        $("#materialInfor").select2("val","");
        selectData = 0;
        $("#s2id_materiallocal .select2-choices").children(".select2-search-choice").remove();
        $("#materiallocal").select2("val","");
        selectData = 0;

    }
    //添加物料详情
    function addDetail(){
        if($("#inForm #id").val()==""){
            layer.alert("请先保存表单信息！");
            return;
        }
        if($("#materialInfor").val()==""){
            layer.alert("请选择物料！");
        }
        if($("#materiallocal").val()==""){
            layer.alert("请选择库位！");
        }
        else{
            var id =$("#inForm #id").val();
            $.ajax({
                type:"POST",
                url:context_path + "/packageIn/saveDetail",
                data:{packagemanageinid:id,stockId:$("#materiallocal").val(),materialId:$("#materialInfor").val()},
                dataType:"json",
                success:function(data){
                    removeChoice();   //清空下拉框中的值
                    if(Boolean(data.result)){
                        layer.msg("添加成功",{icon:1,time:1200});
                        //重新加载详情表格
                        reloadDetailTableList();
                    }else{
                        layer.msg(data.msg,{icon:2,time:1200});
                    }
                }
            });
        }
    }
    //工具栏
    $("#__toolbar__-c").iToolBar({
        id:"__tb__01",
        items:[
            {label:"删除", onclick:delDetail},
        ]
    });
    //删除物料详情
    function delDetail(){
        var ids = jQuery("#grid-table-c").jqGrid("getGridParam", "selarrrow");
        $.ajax({
            url:context_path + "/packageIn/deleteDetail.do?ids="+ids,
            type:"POST",
            dataType:"JSON",
            success:function(data){
                if(Boolean(data.result)){
                    layer.msg("操作成功！");
                    reloadDetailTableList();
                }else{
                    layer.msg(data.msg);
                }
            }
        });
    }
    function reloadDetailTableList(){
        $("#grid-table-c").jqGrid("setGridParam",
            {
                url:context_path + "/packageIn/detailList.do?pId="+$("#inForm #id").val(),
                postData: {queryJsonString:""} //发送数据  :选中的节点
            }).trigger("reloadGrid");
    }
    $("#materialInfor").select2({
        placeholder: "选择物料",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/packageIn/getMListByInId",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
    $("#materiallocal").select2({
        placeholder: "选择库位",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/packageIn/getSelectInLocation",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
    $("#inForm #userId").select2({
        placeholder: "选择操作人",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        width: 220,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/packageIn/getUserSelect",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
    $("#inForm #packageId").select2({
        placeholder: "选择翻包编号",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/packageIn/getPackageList",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
    $.ajax({
        type:"POST",
        url:context_path + "/packageIn/findById",
        data:{id:$("#inForm #id").val()},
        dataType:"json",
        success:function(data){
            $("#inForm #userId").select2("data", {
                id: data.userId,
                text: data.userName
            });
            $("#inForm #packageId").select2("data", {
                id: data.packageId,
                text:data.text
            });
        }
    });

    /**
     * 翻包入库提交操作
     */
    function submitPackageIn(){
        if($("#inForm #id").val()==""){
            layer.msg("请先保存表头信息！",{icon:2,time:1200});
            return;
        }
        layer.confirm("确定提交的装箱入库？", function () {
            $.ajax({
                type:"post",
                url:context_path+"/packageIn/submitPackageIn.do?packageInId="+$("#id").val(),
                dataType:"json",
                success:function(data){
                    if(Boolean(data.result)){
                        layer.msg(data.msg);
                        reloadDetailTableList();
                    }else{
                        layer.alert(data.msg,{icon: 2, time: 1000});
                    }
                }
            });
        });
    }


</script>

